﻿using System;
using System.Linq;
using System.IO;
using PSE.Deployment.Engine.CustomEventArgs;
using PSE.Deployment.Setup.Wizard;
using PSE.Deployment.SetupBase;
using PSE.Deployment.SetupBase.Parameter.Enums;
using PSE.Deployment.Util;

namespace PSE.Deployment.Setup.Main
{
    public class PSEMain : SetupMain
    {
        #region Fileds

        private WizardGroup _wizardGroup;

        #endregion

        #region Constructor

        public PSEMain()
            : base()
        {
            this.LogPath = Path.Combine(Environment.GetEnvironmentVariable("TEMP", EnvironmentVariableTarget.Machine), System.Configuration.ConfigurationSettings.AppSettings["LogFilePath"]);
            this.HosterName = System.Configuration.ConfigurationSettings.AppSettings["HosterName"];
        }

        #endregion

        #region Group Events

        protected override void SetupMain_ExecutionStarted(object sender, ExecutionStartedEventArgs e)
        {
            base.SetupMain_ExecutionStarted(sender, e);

            //muda o estados dos grupos para Install = True, pois não há tela de seleção de componentes
            Configuration.SystemInfo.Groups.SelectDeep(g => g.SubGroups).SelectDeep(g => g.Dependencies).ToList().ForEach(g => g.Install = true);
        }

        protected override void SetupMain_ExecutionFinished(object sender, ExecutionFinishedEventArgs e)
        {
            base.SetupMain_ExecutionFinished(sender, e);

            EnableNetTcpPortSharingService();
        }

        private static void EnableNetTcpPortSharingService()
        {
            PSE.Deployment.Util.WindowsService.ChangeStartType("NetTcpPortSharing", System.ServiceProcess.ServiceStartMode.Automatic);
        }

        private void _wizardGroup_ExecutionFinished(object sender, ExecutionFinishedEventArgs e)
        {
            if (e.OriginalSource is WizardGroup)
            {
                if (!SetupMainFactory.GetInstance<PSEMain>().Parameter.IsInstalled)
                {
                    SetupMainFactory.GetInstance<PSEMain>().Parameter.SetupMode = SetupMode.Install;
                    AddInstallStep();
                }
                else
                {
                    AddChangeStep();
                }
            }
        }

        #endregion

        #region Virtual Methods

        protected override void AddWizardStep()
        {
            _wizardGroup = new WizardGroup(this);
            _wizardGroup.ExecutionFinished += new EventHandler<ExecutionFinishedEventArgs>(_wizardGroup_ExecutionFinished);
            this.Steps.Add(_wizardGroup);
        }

        #endregion
    }
}